package org.book.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.book.dao.UserBean;
import org.book.service.UserService;

/**
 * Servlet implementation class UsersServlet
 */
@WebServlet("/UsersServlet")
public class UsersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UsersServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		
		
		
		//搜索
		String textName = request.getParameter("textName");
		
		//页码
		Object obj = request.getParameter("pageCurrent");
		//修改删除之后保持页码
		Object obj2 = request.getAttribute("pageCurrent2");
		
		UserService userService = new UserService();
		
		List<UserBean> list = new ArrayList<>();
		
		int pageCurrent = 1;
		
		if(obj!=null) {
			pageCurrent = Integer.parseInt(obj.toString());
		}
		//页码
		if(obj2!=null) {
			pageCurrent = Integer.parseInt(obj2.toString());
		}
		//搜索
		if(textName!=null) {
			list = userService.getLike(textName);
		}
		//显示
		else {
			list = userService.getList(pageCurrent,10);
		}
		
		
		request.setAttribute("list", list);
		
		request.setAttribute("pageCurrent", pageCurrent);
		
		request.setAttribute("count", userService.getCount());
		
		//借阅跳转判断
		String book = request.getParameter("book_id");
		if(book!=null) {
			int book_id = Integer.parseInt(book);
			request.getSession().setAttribute("book_id", book_id);
			//30秒后失效
			request.getSession().setMaxInactiveInterval(30);
		}
		request.getRequestDispatcher("pages/home/user.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
